package com.android.corestat.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.android.corestat.service.WorkingService;
import com.android.corestat.utils.CSLog;

public class NetworkStateReceiver extends BroadcastReceiver {
	private static final String TAG = "cs-netstate";

	@Override
	public void onReceive(Context context, Intent intent) {
		if (null == intent) {
			return;
		}
		if (!ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
			return;
		}
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = null;
		try {
			ni = cm.getActiveNetworkInfo();
		} catch (Exception e) {
		}
		if (ni == null) {
			return;
		}

		if (!WorkingService.isServiceTaskFinished(context)) {
			if (!WorkingService.isServiceRunning(context)) {
				CSLog.e(TAG, "NetworkStateReceiver startWorkingService");
				WorkingService.startWorkingService(context, 0);
			}
			Intent i = new Intent(context, WorkingService.class);
			i.setAction(ConnectivityManager.CONNECTIVITY_ACTION);
			context.startService(i);
		}
	}
}
